<template>
  <div class="selector-modal-body">
    <!-- 左侧：部门数据源（树形） -->
    <div class="selector-list">
      <el-tree
        ref="treeRef"
        :data="deptTree"
        node-key="id"
        :props="treeProps"
        :default-checked-keys="defaultCheckedKeys"
        :show-checkbox="multiple"
        highlight-current
        @check="onCheck"
        @node-click="onNodeClick"
        style="width: 100%"
      />
    </div>
    <!-- 右侧：已选列表 -->
    <div class="selector-selected">
      <div class="selected-title">已选择</div>
      <el-tag
        v-for="item in selectedList"
        :key="item.id"
        closable
        @close="removeSelected(item)"
        style="margin: 4px 4px 0 0;"
      >
        {{ item.name }}
      </el-tag>
      <div v-if="!selectedList.length" class="empty-selected">暂无选择</div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, computed, onMounted, nextTick } from 'vue'
import { listDeptApi } from '@/api/system/organize/dept.api'

// 引入统一的夜间模式样式
import '../Workflow/styles/dark-theme.css'

const props = defineProps({
  multiple: { type: Boolean, default: true },
  selectedList: { type: Array, default: () => [] },
  // 原始人员配置（用于限制模式）
  originalPersonnel: { type: Array, default: () => [] },
  // 是否限制模式
  limitedMode: { type: Boolean, default: false }
})
const emit = defineEmits(['update:selectedList', 'close'])

// 部门树数据
const deptTree = ref([])
const treeRef = ref()
const treeProps = { label: 'name', children: 'children' }

function fetchDeptList() {
  listDeptApi().then(res => {
    // 处理返回的数据，直接使用data字段
    const deptData = res?.data || res || []
    deptTree.value = deptData
    // 数据加载完成后，设置默认选中项
    nextTick(() => {
      if (treeRef.value && Array.isArray(selectedIds.value) && selectedIds.value.length > 0) {
        treeRef.value.setCheckedKeys(selectedIds.value)
      }
    })
  }).catch(err => {
    console.error('DeptSelector - API error:', err)
  })
}

// 选中项
const selectedIds = ref([])
watch(() => props.selectedList, (val) => {
  // 确保selectedIds始终是数组
  if (Array.isArray(val)) {
    selectedIds.value = val.map(item => item.id).filter(id => id != null)
  } else {
    selectedIds.value = []
  }
  // 当外部传入选中项时，更新树的选中状态
  nextTick(() => {
    if (treeRef.value && Array.isArray(selectedIds.value) && selectedIds.value.length > 0) {
      treeRef.value.setCheckedKeys(selectedIds.value)
    }
  })
}, { immediate: true })

// 计算已选列表
const selectedList = computed(() => {
  const flat = []
  // 确保selectedIds是数组
  if (!Array.isArray(selectedIds.value)) {
    return flat
  }
  
  function traverse(nodes) {
    if (!Array.isArray(nodes)) return
    nodes.forEach(n => {
      // 只添加明确选中的节点
      if (selectedIds.value.includes(n.id)) {
        flat.push(n)
      }
      if (n.children && Array.isArray(n.children)) traverse(n.children)
    })
  }
  traverse(deptTree.value)
  return flat
})

// 计算默认选中项
const defaultCheckedKeys = computed(() => {
  return Array.isArray(selectedIds.value) ? selectedIds.value : []
})

function onCheck(nodeData, checkedInfo) {
  // 获取所有选中的节点ID（包括父节点和子节点）
  const allCheckedKeys = checkedInfo.checkedKeys || []
  
  // 智能选择逻辑：分析哪些应该显示在右侧
  const displayKeys = getDisplayKeys(deptTree.value, allCheckedKeys)
  
  selectedIds.value = displayKeys
  emit('update:selectedList', selectedList.value)
}

// 智能选择逻辑：决定哪些节点应该显示在右侧
function getDisplayKeys(nodes, checkedKeys) {
  const displayKeys = []
  
  function analyzeNode(node) {
    if (!node.children || node.children.length === 0) {
      // 叶子节点：如果被选中，直接显示
      if (checkedKeys.includes(node.id)) {
        displayKeys.push(node.id)
      }
    } else {
      // 父节点：检查子节点状态
      const childKeys = node.children.map(child => child.id)
      const checkedChildKeys = childKeys.filter(key => checkedKeys.includes(key))
      
      if (checkedChildKeys.length === 0) {
        // 没有子节点被选中：如果父节点被选中，显示父节点
        if (checkedKeys.includes(node.id)) {
          displayKeys.push(node.id)
        }
      } else if (checkedChildKeys.length === childKeys.length) {
        // 所有子节点都被选中：只显示父节点，不显示子节点
        displayKeys.push(node.id)
        // 不递归处理子节点，因为我们已经决定显示父节点
        return
      } else {
        // 部分子节点被选中：显示被选中的子节点，不显示父节点
        checkedChildKeys.forEach(key => {
          displayKeys.push(key)
        })
      }
      
      // 递归处理子节点
      node.children.forEach(child => {
        analyzeNode(child)
      })
    }
  }
  
  nodes.forEach(node => {
    analyzeNode(node)
  })
  
  return displayKeys
}

function onNodeClick(node) {
  if (!props.multiple) {
    // 单选模式：只选择当前点击的节点
    selectedIds.value = node && node.id ? [node.id] : []
    emit('update:selectedList', node ? [node] : [])
  }
}

function removeSelected(item) {
  // 获取当前树中所有选中的节点
  const currentCheckedKeys = getCurrentCheckedKeys()
  
  // 从选中项中移除要删除的项
  const updatedCheckedKeys = currentCheckedKeys.filter(id => id !== item.id)
  
  // 重新应用智能选择逻辑
  const displayKeys = getDisplayKeys(deptTree.value, updatedCheckedKeys)
  
  selectedIds.value = displayKeys
  
  // 同时更新树的选中状态
  if (treeRef.value) {
    treeRef.value.setCheckedKeys(updatedCheckedKeys)
  }
  
  emit('update:selectedList', selectedList.value)
}

// 获取当前树中所有选中的节点
function getCurrentCheckedKeys() {
  // 从树的选中状态获取所有选中的节点
  if (treeRef.value) {
    return treeRef.value.getCheckedKeys()
  }
  return selectedIds.value
}

onMounted(fetchDeptList)
</script>
<style scoped>
.selector-modal-body {
  display: flex;
  gap: 16px;
  min-height: 480px;
  height: 60vh;
  max-height: 80vh;
  overflow: auto;
}
.selector-list {
  flex: 2;
  background: #f7f8fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.selector-selected {
  flex: 1;
  background: #f5f7fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 180px;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e4e7ed;
}
.selected-title {
  font-weight: bold;
  margin-bottom: 8px;
}
.empty-selected {
  color: #bbb;
  margin-top: 12px;
}
</style> 